﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;

using EyesOfTheDragon.Events;

using Anthem.GameScreens;

using Anthem.Components;
using XRpgLibrary.Events;
using EyesOfTheDragon.Globals;

namespace EyesOfTheDragon.Components
{
    public class Doors :IUpdate, IPauseable
    {
        private const int gidDoor0 = 192;
        private const int playerSpawn0 = 216;
        private const string triggerLayer = "triggersLayer";
        public bool Enabled
        {
            get
            {
                return true;
            }
            set { }
        }
        public static Doors Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Doors();
                return _instance;
            }
        }

        public void Update(GameTime gt)
        {
            bool foundDoor = false;
            int doorNum = 0;
            for (int i = 0; i < 8;i++)
            {
                if (Player.Instance.PlayerLevel + 1 < i)
                    continue;
                List<GTile> tiles = map.Instance.getLayer(triggerLayer).getTiles(MapVariables.BaseDoorGID + i);
                foreach( GTile t in tiles)
                {

                    if (Player.Instance.Sprite.getRect().Intersects(new Rectangle(t.Position.X, t.Position.Y, map.Instance.tilewidth, map.Instance.tileheight)))
                    {
                        foundDoor = true;
                        doorNum = i+1;
                        break;
                    }

                }
                if (foundDoor)
                    break;
            }
            if (foundDoor)
            {
                Monster.Instance.Clear();
                int lastMap = map.Instance.CurrentMap;
                EventRouter.Instance.update(MonsterGenerator.Map_Changing);
                map.LoadFromXml(GamePlayScreen.Instance.GameRef, doorNum);

                List<GTile> tiles = map.Instance.getLayer(triggerLayer).getTiles(MapVariables.BasePlayerSpawnGID + (lastMap - 1));
                if (tiles.Count > 0)
                {
                    Player.Instance.Sprite.position = new Vector2(tiles[0].Position.X, tiles[0].Position.Y);
                    
                }
                Player.Instance.Sprite.Scale = new Vector2(map.Instance.MapScale, map.Instance.MapScale);
                return;
            }
            
        }
        private static Doors _instance;
    }
}
